const { User } = require('../model')
const jwt = require('../util/jwt')
const { jwtSecret } = require('../config/config.default')

exports.login = async (req, res, next) => {
  try {
    //1数据验证 2生成token 3发送成功相应并且包含token
    // jwt不加密 最好加密
    const user = req.user.toJSON()  //magoose 转json
    const token = await jwt.sign({
      userId: user._id
    }, jwtSecret, { expiresIn: 60 * 60 * 240 })
    delete user.password
    res.status(200).json({
      ...user,
      token
    })
  } catch (err) {
    next(err)
  }
}

exports.registration = async (req, res, next) => {
  try {
    //1.获取请求体
    //2.数据验证 基本验证 业务数据验证 
    //3.验证通过，保存到数据库
    console.log(req)
    let user = new User(req.body.user)
    await user.save()

    user = user.toJSON()
    //直接删删不掉 因为mango进行了特殊处理
    delete user.password
    //4.返回相应体

    res.status(201).json({
      user
    })
  } catch (err) {
    next(err)
  }
}

exports.updateUser = async (req,res, next) => {
  try {
    let userinfo = req.body['user']
    // console.log(userinfo.username)
    let username = { username: userinfo.username }
    let str = { "_id": userinfo._id}
    await User.updateOne(str, {$set: username},(res,err)=>{
      if(res){
        res.send('updateUser')
      }else{
        console.log(err)
      }
    })
    res.send('updateUser')
  } catch (err) {
    next(err)
  }
}

exports.getCurrentUser = async (req,res, next) => {
  try {
    res.status(200).json({
      user: req.user
    })
  } catch (err) {
    next(err)
  }
}

